package com.onlinewebgames.login.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.onlinewebgames.login.model.User;

public class UserDAO {
	private static UserDAO	instance;
	private static UserDB		userDB;

	private UserDAO(Context context) {
		userDB = new UserDB(context, UserDB.nombreBBDD, null, 1);
	}

	public static void init (Context context) {
		instance = new UserDAO(context);
	}

	public static UserDAO getInstance () {
		return instance;
	}

	public boolean changeUser (User user) {
		if (getUser() != null) {
			borrarUser();
		}
		if (insertUser(user) != -1) {
			return true;
		}
		return false;

	}

	public void borrarUser () {
		SQLiteDatabase db = userDB.getWritableDatabase();

		db.execSQL("delete from " + UserDB.nombreTabla);

		db.close();
	}

	public long insertUser (User user) {
		SQLiteDatabase db = userDB.getWritableDatabase();

		ContentValues registro = UserDB.transformToRegistro(user);
		long retorno = db.insert(UserDB.nombreTabla, null, registro);

		db.close();
		return retorno;
	}

	public long updateUser (User user) {
		SQLiteDatabase db = userDB.getWritableDatabase();

		ContentValues registro = UserDB.transformToRegistro(user);
		long retorno = db.update(UserDB.nombreTabla, registro,
				"id=" + user.getId(), null);

		db.close();
		return retorno;
	}

	public User getUser () {
		SQLiteDatabase db = userDB.getReadableDatabase();

		User user = UserDB.transformToUser(db.rawQuery("select * from "
				+ UserDB.nombreTabla, null));
		db.close();
		return user;
	}

}
